#include "Precompile.h"
#include "ThreadFactory.h"
#include "BoostThread.h"
#include "BoostMutex.h"

namespace ThreadLib{
	static std::set<boost::shared_ptr<Thread>> m_threads;
	static MutexPtr m_threadMutex;

	boost::shared_ptr<Thread> ThreadFactory::spawnThread(boost::function<void(void)> function){
		if(!m_threadMutex){
			m_threadMutex = spawnMutex();
		}

		boost::shared_ptr<Thread> ptr = boost::shared_ptr<Thread>(new BoostThread(function));

		m_threadMutex->lock();
		m_threads.insert(ptr);
		m_threadMutex->unlock();
		return ptr;
	}

	boost::shared_ptr<Mutex> ThreadFactory::spawnMutex(){
		return boost::shared_ptr<Mutex>(new BoostMutex);
	}

	void ThreadFactory::releaseThread(boost::shared_ptr<Thread> thread){
		m_threadMutex->lock();
		m_threads.erase(thread);
		m_threadMutex->unlock();
	}
}